package com.zhang.util;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * User: 张
 * Date: 2024-11-17
 * Time: 11:07
 * Description:
 */
@Component
public class DeviceRedisUtil {
    @Autowired
    private RedisUtil redisUtil;
    private final String redisName = "DeviceList";
    private Map<String, String> post(){
        String jsonStr = (String) redisUtil.get(redisName);
        return JSON.parseObject(jsonStr, Map.class);
    }
    public void initDeviceList(){
        Map<String, String> map = new HashMap<>();
        redisUtil.set(redisName,JSON.toJSONString(map));
        System.out.println("设备列表初始化");
    }
    public void clearDeviceList(){
        redisUtil.popValue(redisName);
        System.out.println("设备列表清空");
    }

    public void addDevice(String channelId,String ip){
        Map<String, String> map = post();
        map.put(channelId,ip);
        redisUtil.set(redisName,JSON.toJSONString(map));
    }

    public String getIp(String channelId){
        Map<String, String> map = post();
        return map.get(channelId);
    }
    public String getChannelId(String ip){
        Map<String, String> map = post();
        if (map.containsValue(ip)){
            for (Map.Entry<String, String> entry : map.entrySet()) {
                if (entry.getValue().equals(ip)){
                    return entry.getKey();
                }
            }
        }else {
            return null;
        }
        return null;
    }
    public Map<String,String> getAllDevice(){
        return post();
    }
    public Integer getDeviceSize(){
        if (redisUtil.get(redisName) == null) return null;
        String jsonStr = (String) redisUtil.get(redisName);
        return JSON.parseObject(jsonStr, Map.class).size();
    }

    public void removeDevice(String valueToDelete){
        Map<String, String> map = post();
        if (map.containsKey(valueToDelete))
            map.remove(valueToDelete);
        else {
            for (Map.Entry<String, String> entry : map.entrySet()) {
                if (entry.getValue().equals(valueToDelete)) {
                    map.remove(entry.getKey());
                }
            }
        }
        redisUtil.set(redisName,JSON.toJSONString(map));
    }
}














